package one.stand.model;

import one.stand.advice.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Objects;

/**
 * 返回数据类
 *
 * @param <T>
 * @author Administrator
 */
public class ResultModel<T> implements Serializable {
    private static final Logger log = LoggerFactory.getLogger(ResultModel.class);
    private static final long serialVersionUID = 1L;

    private Integer code;
    private String message;
    private T data;
    @Deprecated
    private boolean isSuccess;

    public ResultModel() {
    }

    public ResultModel(T t) {
        this.code = ResultEnum.SUCCESS.getCode();
        this.message = ResultEnum.SUCCESS.getMessage();
        this.data = t;
    }

    public ResultModel(Integer code, String messages) {
        this.code = code;
        this.message = messages;
    }

    /**
     * 参数缺失
     */
    public static <T> ResultModel<T> checkParamFail() {
        return fail(ResultEnum.NO_PARAM);
    }

    /**
     * 操作失败
     */
    public static <T> ResultModel<T> error() {
        return fail(ResultEnum.ERROR);
    }

    /**
     * 账号过期
     */
    public static <T> ResultModel<T> account() {
        return fail(ResultEnum.ACCOUNT);
    }

    public static <T> ResultModel<T> faultTolerant() {
        log.warn("server faultTolerant");
        return fail(ResultEnum.FAULT_TOLERANT);
    }

    /**
     * 无数据
     */
    public static <T> ResultModel<T> noData() {
        return fail(ResultEnum.NO_DATA);
    }

    /**
     * 操作失败 默认201
     */
    public static <T> ResultModel<T> fail() {
        return fail(ResultEnum.FAIL);
    }

    /**
     * 自定义异常消息
     */
    public static <T> ResultModel<T> fail(String message) {
        return fail(ResultEnum.FAIL.getCode(), message);
    }

    /**
     * 操作失败
     */
    public static <T> ResultModel<T> fail(ResultEnum resultEnum) {
        return fail(resultEnum.getCode(), resultEnum.getMessage());
    }

    /**
     * 操作失败
     */
    public static <T> ResultModel<T> fail(Integer code, String message) {
        return new ResultModel<>(code, message);
    }

    /**
     * 操作成功不带参数
     */
    public static <T> ResultModel<T> success() {
        return success(null);
    }

    /**
     * 操作成功带参数
     */
    public static <T> ResultModel<T> success(T t) {
        return new ResultModel<>(t);
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isSuccess() {
        return Objects.nonNull(code) && code.equals(ResultEnum.SUCCESS.getCode());
    }
}
